import modelAbstract from "./modelAbstract"
import {image} from "../service/images"
import config from "../../config"
import playCan from "../canvas/player"
// @ts-ignore
import _ from "lodash"
import {directionEnum} from "../enum/directionEnum";
import touchUtil from "../utils/touch";
import bullet from "../canvas/bullet";
import audio from "../service/audio";

export default class player extends modelAbstract implements IModel {
  name: string = 'player'
  canvas: ICanvas = playCan
  // 事件是否绑定
  bindEvent: boolean = false
  direction: directionEnum = directionEnum.top
  intervalId = null

  image(): HTMLImageElement {
    let direction = this.name + _.upperFirst(this.direction)
    return image.get(direction as keyof typeof config.images)!
  }

  render(): void {
    super.draw()
    if (!this.bindEvent) {
      this.bindEvent = true
      // 按键改变方向
      document.addEventListener('keydown', this.changeDirection.bind(this))
      // 发射子弹
      document.addEventListener('keydown', async (e: KeyboardEvent) => {
        if (e.code === 'KeyJ') {
          await audio.fire()
          bullet.addPlayerBullet(this)
        }
      })
    }
  }


  // 按键改变方向
  changeDirection(e: KeyboardEvent) {
    switch (e.code) {
      case 'KeyW':
        this.direction = directionEnum.top
        break
      case 'KeyS':
        this.direction = directionEnum.bottom
        break
      case 'KeyA':
        this.direction = directionEnum.left
        break
      case 'KeyD':
        this.direction = directionEnum.right
        break
    }
    // @ts-ignore
    clearInterval(this.intervalId)
    this.playMove()
    this.canvas.renderModels()
  }

  // 移动
  playMove() {
    // @ts-ignore
    this.intervalId = setInterval(() => {
      let x = this.position.x
      let y = this.position.y
      switch (this.direction) {
        case 'top':
          y -= 2
          break
        case 'bottom':
          y += 2
          break
        case 'left':
          x -= 2
          break
        case 'right':
          x += 2
          break
      }
      // 碰撞检测
      if (touchUtil.isCanvasTouch(x, y) || touchUtil.isModelTouch(x, y)) {
        // @ts-ignore
        clearInterval(this.intervalId)
      } else {
        this.position.x = x
        this.position.y = y
      }
      this.canvas.renderModels()
    }, 20)
  }
}
